<script setup lang='ts'>
import type { OptionsType, PlusColumn } from 'plus-pro-components'

import {
    useApplyForRelativeSuppliers,
    useGetApplyDetail,
    useGetCategory,
    useGetEnterpriseBrandOptions,
    useGetProvinceCityCounty,
    // useGetSupplierOptions,
    useGetSupplieByTypeOptions,
    useRetryApplyForRelativeSuppliers,
} from '@fl/api/supplier'
import FlUpload from '@fl/components/fl-upload.vue'
import SubmitBtn from '@fl/components/submit-btn.vue'
import { jsonToArray } from '@fl/utils/fn'
import { cascaderValueToString, treeFindLabel } from '@fl/utils/tree'
import { cloneDeep } from 'lodash-es'

const id = defineModel<string>('id', { required: true })
const visible = defineModel<boolean>('visible', { required: true })

const initialState = {
    authTime: [],
    brandId: [],
    catId: [],
    fileList: [],
    region: [],
} as any
const state = ref(cloneDeep(initialState))

const isEdit = computed(() => !!id.value)
const dialogTitle = computed(() => isEdit.value ? '编辑' : '发起申请')
const getEnterpriseBrandParams = computed<string>(() => state.value.supplierId)
// const getSupplierOptionsParams = computed<string>(() => unref(visible) ? '8' : '')
const getSupplierOptionsParams = computed(() => {
    return {
        type: 8,
        visible: unref(visible),
    }
})

const { data: enterpriseBrandData } = useGetEnterpriseBrandOptions(getEnterpriseBrandParams)
const { data: categoryData, isLoading: isGetCategoryLoading } = useGetCategory()
const { isPending: isApplyForRelativeSuppliersPending, mutate: applyForRelativeSuppliers } = useApplyForRelativeSuppliers()
const { isPending: isRetryApplyForRelativeSuppliersPending, mutate: retryApplyForRelativeSuppliers } = useRetryApplyForRelativeSuppliers()
const { data: provinceCityCountyData } = useGetProvinceCityCounty()
// const { data: supplierOptionsData, isLoading: isGetSupplierOptionsLoading } = useGetSupplierOptions(getSupplierOptionsParams)
const { data: supplierOptionsData, isLoading: isGetSupplierOptionsLoading } = useGetSupplieByTypeOptions(getSupplierOptionsParams)

const { data: applyDetailData, isLoading: isGetApplyDetailLoading } = useGetApplyDetail(id)

// #region Form
const formRef = ref()
const isFormLoading = computed(() => {
    return isGetApplyDetailLoading.value || isGetCategoryLoading.value || isGetSupplierOptionsLoading.value
})
const isSubmitLoading = computed(() => {
    return isEdit.value ? isRetryApplyForRelativeSuppliersPending.value : isApplyForRelativeSuppliersPending.value
})
const brandOptions = computed(() => state.value.supplierId ? (enterpriseBrandData.value || []) : [])

const columns: PlusColumn[] = [
    {
        fieldProps: {
            disabled: isEdit.value,
        },
        label: '供应商',
        options: supplierOptionsData as OptionsType,
        prop: 'supplierId',
        valueType: 'select',
    },
    {
        fieldProps: {
            onChange: (value: string[][]) => {
                state.value.catName = cascaderValueToString(value, {
                    treeData: categoryData.value,
                })
            },
            props: { multiple: true },
        },
        label: '授权品类',
        options: categoryData as OptionsType,
        prop: 'catId',
        valueType: 'cascader',
    },
    {
        fieldProps: {
            multiple: true,
            onChange: (value: string[]) => {
                state.value.brandName = value.map((item: string) => brandOptions.value.find((option: any) => option.value === item)!.label)
                    .join(',')
            },
        },
        label: '代理品牌',
        options: brandOptions,
        prop: 'brandId',
        valueType: 'select',
    },
    {
        fieldProps: {
            endPlaceholder: '请选择结束时间',
            startPlaceholder: '请选择开始时间',
            type: 'daterange',
            valueFormat: 'YYYY-MM-DD',
        },
        label: '授权时间',
        prop: 'authTime',
        valueType: 'date-picker',
    },
    {
        label: '授权地区',
        options: provinceCityCountyData as OptionsType,
        prop: 'region',
        valueType: 'cascader',
    },
    {
        label: '厂家授权函',
        prop: 'fileList',
    },
]

const rules = {
    authTime: [
        {
            message: '请选择授权时间',
            required: true,
            trigger: 'change',
        },
    ],
    brandId: [
        {
            message: '请选择代理品牌',
            required: true,
            trigger: 'change',
        },
    ],
    catId: [
        {
            message: '请选择授权品类',
            required: true,
            trigger: 'change',
        },
    ],
    fileList: [
        {
            message: '请上传厂家授权函',
            required: true,
            trigger: 'change',
        },
    ],
    region: [
        {
            message: '请选择授权地区',
            required: true,
            trigger: 'change',
        },
    ],
    supplierId: [
        {
            message: '请选择供应商',
            required: true,
            trigger: 'change',
        },
    ],
}
// #endregion

// #region UI Listener
function onSubmitBtnClick() {
    formRef.value.handleSubmit()
}

function submit() {
    const data = cloneDeep(state.value)
    const params = {
        ...data,
        brandId: JSON.stringify(data.brandId),
        catId: JSON.stringify(data.catId),
        city: treeFindLabel({ targetValue: data.region![1], treeData: provinceCityCountyData.value! }),
        county: treeFindLabel({ targetValue: data.region![2], treeData: provinceCityCountyData.value! }),
        endTime: data.authTime![1],
        file: JSON.stringify(data.fileList),
        fileList: undefined,
        province: treeFindLabel({ targetValue: data.region![0], treeData: provinceCityCountyData.value! }),
        region: JSON.stringify(data.region),
        startTime: data.authTime![0],
    }

    const fn = isEdit.value ? retryApplyForRelativeSuppliers : applyForRelativeSuppliers
    fn(params, {
        onSuccess() {
            ElMessage.success('操作成功')
            closed()
        },
    })
}

function onCancelBtnClick() {
    closed()
}

function closed() {
    visible.value = false
    if (isEdit.value) {
        id.value = ''
    }
    else {
        state.value = cloneDeep(initialState)
        formRef.value.formInstance?.resetFields()
    }
}
// #endregion

watch(() => state.value.supplierId, (newValue, oldValue) => {
    if (oldValue || !newValue) {
        state.value.brandId = []
    }
})

watchEffect(() => {
    if (isEdit.value && applyDetailData.value) {
        const data = cloneDeep(applyDetailData.value)
        const fileList = jsonToArray(data.file)
        Object.assign(state.value, data, {
            authTime: [data.startTime, data.endTime],
            brandId: JSON.parse(data.brandId),
            catId: JSON.parse(data.catId),
            fileList,
            region: JSON.parse(data.region),
        })
    }
})
</script>

<template>
    <PlusDialog v-model="visible"
                :title="dialogTitle"
                width="700"
                close-on-press-escape
                @closed="closed"
    >
        <el-skeleton v-if="isFormLoading"
                     animated
        />

        <PlusForm v-else
                  ref="formRef"
                  v-model="state"
                  :columns="columns"
                  :label-width="100"
                  :rules="rules"
                  :has-footer="false"
                  @submit="submit"
        >
            <template #plus-field-fileList>
                <FlUpload v-model="state.fileList"
                          tips
                          accept=".docx,.pdf,.jpg,.jpeg,.png"
                          list-type="text"
                />
            </template>
        </PlusForm>

        <template #footer>
            <div class="mx-auto">
                <el-button @click="onCancelBtnClick">
                    取消
                </el-button>

                <SubmitBtn type="primary"
                           :loading="isSubmitLoading"
                           @click="onSubmitBtnClick"
                >
                    提交
                </SubmitBtn>
            </div>
        </template>
    </PlusDialog>
</template>
